package com.bw.aop;

import cn.hutool.json.JSONUtil;
import com.bw.domain.Log;
import com.bw.domain.Users;
import com.bw.service.LogService;
import com.bw.service.UsersService;
import com.bw.utils.common.JWTUtils;
import com.bw.utils.common.Result;
import jdk.nashorn.internal.ir.debug.JSONWriter;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Aspect
@Component
@Slf4j
public class aopLog {
    @Autowired
    UsersService usersService;
    @Autowired
    LogService logService;

    @Autowired
    HttpServletRequest request;

    @Around(value = "@annotation(Log)")
    public Object log(ProceedingJoinPoint pjp) throws Throwable {
        String userId = JWTUtils.getUserId();
        String username="未知用户";
        if(userId!=null){
            Users users = usersService.getById(userId);
             username = users.getUsername();
        }
        String url = request.getRequestURI();
        String ip = request.getLocalAddr();
        String args = JSONUtil.toJsonStr(pjp.getArgs());
        Log log1 = new Log(null, ip, username, url, args, new Date());
        boolean save = logService.save(log1);
        log.info(JSONUtil.toJsonStr(log1));
        return pjp.proceed();

    }

}
